package com.yincheng.oes.business.util;

import com.yincheng.oes.business.consist.Consists;
import com.yincheng.oes.business.exam.export.ZipAttachments;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: yangsy
 * @Contact: 446948434@qq.com
 * @Date: 2021/7/25 19:41
 * @Version: 1.0
 * @Description:
 */
public class ExportFileUtils {

    /**
     * 日志
     */
    private static final Logger logger = LogManager.getLogger(ExportFileUtils.class);

    public static ZipAttachments getZipAttachments(String paperName, File zipfile) {
        return new ZipAttachments() {

            private final long length = zipfile.length();

            @Override
            public long getSize() {
                return length;
            }

            @Override
            public String getName() {
                return paperName + ".zip";
            }

            @Override
            public void exportToOutputStream(OutputStream outputStream) throws IOException {
                try {
                    if (zipfile.exists()) {
                        org.apache.commons.io.FileUtils.copyFile(zipfile, outputStream);
                    } else {
                        throw new UnsupportedOperationException("not support repeated calls.");
                    }
                } finally {
                    if (zipfile.exists()) {
                        zipfile.delete();
                    }
                }
            }
        };
    }

    /**
     * 获取临时目录带当前日期
     *
     * @return basePath/tmp/yyMMdd/
     */
    public static File getTmpBaseFile() {
        File baseFile = getBaseFile();
        String yyMMdd = TimeUtils.getYYMMdd();
        File file = FileUtils.getFile(baseFile, Consists.TEMP_FILE_PARENT_PATH, yyMMdd);
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException e) {
            logger.error("getTmpBaseFile error", e);

        }
        return file;
    }

    public static File getBaseFile() {
        return FileUtils.getFile(Consists.BASE_FILE_PATH);
    }

    /**
     * 获取临时目录路径
     *
     * @return basePath/tmp
     */
    public static String getTmpPath() {
        return getBaseFile() + File.separator + Consists.TEMP_FILE_PARENT_PATH;
    }

}
